import React from 'react'
import { Route } from 'react-router'
import { Helmet } from 'react-helmet'
import { sprintf } from 'sprintf-js'
import { Button, Result } from 'antd'
import { history } from '@/plugins/history'

const FrontendAuth = ({
  config,
  routerConfig,
  location
}: {
  config: any,
  routerConfig: any,
  location: any
}) => {
  const { pathname } = location
  const isLogin = sessionStorage.getItem('username')

  const targetRouterConfig = routerConfig.find(
    (item: any) => item.path === pathname
  )

  const LHelmet = (ops: { title?: string }) => (
    <Helmet title={sprintf(config.title, ops.title)} />
  )

  const Result404 = () => (
    <div>
      <LHelmet title='页面不存在' />

      <Result
        status='404'
        title='404'
        subTitle='对不起，您访问的页面不存在。'
        extra={<Button type='primary' onClick={() => history.push('/')}>返回首页</Button>}
      />
    </div>
  )

  if (targetRouterConfig && !targetRouterConfig.auth && !isLogin) {
    const { component } = targetRouterConfig
    return (
      <div>
        <LHelmet title={targetRouterConfig?.meta?.title ?? 'index'} />

        <Route exact path={pathname} component={component} />
      </div>
    )
  }

  if (isLogin) {
    if (targetRouterConfig) {
      return (
        <div>
          <LHelmet title={targetRouterConfig?.meta?.title ?? 'index'} />

          <Route path={pathname} component={targetRouterConfig.component} />
        </div>
      )
    } else {
      return <Result404 />
    }
  } else {
    if (targetRouterConfig && targetRouterConfig.auth) {
      return <div>需要登录</div>
    } else {
      return <Result404 />
    }
  }
}

export default FrontendAuth
